package com.ostrich.library_net

import android.util.Log
import androidx.lifecycle.LiveData
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/24 10:14
 * @Description : LivedataCallAdapter
 */
class LivedataCallAdapter<T>(val returnType: Type): CallAdapter<T,LiveData<T>> {
    override fun responseType(): Type {
        return returnType
    }

    override fun adapt(call: Call<T>): LiveData<T> {
        return object :LiveData<T>(){
            val atomicBoolean = AtomicBoolean(false)
            override fun onActive() {
                super.onActive()
                if (atomicBoolean.compareAndSet(false,true)){
                    call.enqueue(object :Callback<T>{
                        override fun onResponse(call: Call<T>, response: Response<T>) {
                            Log.d("livedata","onResponse")
                            if(response.code() == 200){
                                postValue(response.body())
                            }
                        }

                        override fun onFailure(call: Call<T>, t: Throwable) {
                            Log.d("livedata","onFailure")
                            //失败原因返回去
                            val baseResponse = BaseResponse<Any>(code = 500, message = t.message, itemList = mutableListOf<Any>())
                            postValue(baseResponse as T)

                        }

                    })
                }
            }
        }
    }
}